package com.example.owner.lettery1.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.webkit.WebView;

import com.example.owner.lettery1.R;
import com.example.owner.lettery1.modlus.NetApi;
import com.example.owner.lettery1.modlus.SingleBean;
import com.example.owner.lettery1.utils.AppManager;
import com.example.owner.lettery1.utils.InstallUtil;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity implements BackHandledFragment.BackHandledInterface{

    private static final String TAG = "MainActivity";
    public final static String DOWNLOAD_KEY = "DOWNLOAD_KEY";
    public final static String FILE_KEY = "FILE_KEY";
    @BindView(R.id.bnve)
    BottomNavigationViewEx bnve;
    private WebView mWebView;
    private Fragment currentFragment;
    private long beforeTime;
    private BackHandledFragment mBackHandedFragment;
    private boolean hadIntercept;
    private boolean createDownload = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final BottomNavigationViewEx bnve = (BottomNavigationViewEx) findViewById(R.id.bnve);
        createDownload = getIntent().getBooleanExtra(DOWNLOAD_KEY, false);
        add(HomeFragment.newInstance(), R.id.main_content_fl, "HomeFragment");

        bnve.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.i_home:
                        add(HomeFragment.newInstance(), R.id.main_content_fl, "HomeFragment");
                        break;
                    case R.id.i_cup:
                        add(OpenLotteryRoomFragment.Companion.newInstance(), R.id.main_content_fl, "OpenLotteryRoomFragment");
                        break;
                    case R.id.i_news:
                        add(NewsFragment.newInstance(), R.id.main_content_fl, "NewsFragment");
                        break;
                    case R.id.i_service:
                        add(ServiceFragment.newInstance(), R.id.main_content_fl, "ServiceFragment");
                        break;
                }

                return true;
            }
        });

        ButterKnife.bind(this);
        arouse();
    }


    //判断fragment的加载是否重叠
    public void add(Fragment fragment, int id, String tag) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        //优先检查，fragment是否存在，避免重叠
        Fragment tempFragment = (Fragment) fragmentManager.findFragmentByTag(tag);
        if (tempFragment != null) {
            fragment = tempFragment;
        }
        if (fragment.isAdded()) {
            addOrShowFragment(fragmentTransaction, fragment, id, tag);
        } else {
            if (currentFragment != null && currentFragment.isAdded()) {
                fragmentTransaction.hide(currentFragment).add(id, fragment, tag).commit();
            } else {
                fragmentTransaction.add(id, fragment, tag).commit();
            }
            currentFragment = fragment;
        }
    }

    /**
     * 添加或者显示 fragment
     *
     * @param fragment
     */
    private void addOrShowFragment(FragmentTransaction transaction, Fragment fragment, int id, String tag) {
        if (currentFragment == fragment)
            return;
        if (!fragment.isAdded()) { // 如果当前fragment未被添加，则添加到Fragment管理器中
            transaction.hide(currentFragment).add(id, fragment, tag).commit();
        } else {
            transaction.hide(currentFragment).show(fragment).commit();
        }
        if (currentFragment != null) {
            currentFragment.setUserVisibleHint(false);
        }
        currentFragment = fragment;
        if (currentFragment != null) {
            currentFragment.setUserVisibleHint(true);
        }
    }


    @Override
    public void setSelectedFragment(BackHandledFragment selectedFragment) {
        this.mBackHandedFragment = selectedFragment;
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    @Override
    public void onBackPressed() {
        if(mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()){
            if(getSupportFragmentManager().getBackStackEntryCount() == 0){
                super.onBackPressed(); //退出
            }else{
                getSupportFragmentManager().popBackStack(); //fragment 出栈
            }
        }
    }

    /**
     * 连续点击两次退出程序 间隔时间在2500
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - beforeTime) > 2500) {
                beforeTime = System.currentTimeMillis();
                Log.d(TAG, "onKeyDown: 再按一次退出");
            } else {
                AppManager.getInstance().AppExit(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //广播通知下载
    private void arouse() {
        if (InstallUtil.INSTANCE.checkPackageInfo(NetApi.PACKAGE_NAME)) {
            Intent intent = getPackageManager().getLaunchIntentForPackage(NetApi.PACKAGE_NAME);
            startActivity(intent);
        } else {
            if (createDownload)
                requestPermission();
        }
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter(DOWNLOAD_KEY));
    }
    /**
     * 获取写入权限
     */
    @SuppressLint("CheckResult")
    private void requestPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean)
                            onCreateDownloadService();
                    }
                });
    }

    private void onCreateDownloadService() {
        Intent intent = new Intent(this, DownloadIntentService.class);
        intent.putExtra(DOWNLOAD_KEY, SingleBean.Companion.getInstance().getAppConfig().getUrl());
        startService(intent);
    }

    /**
     * 制造广播
     */
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (DOWNLOAD_KEY.equals(intent.getAction())) {
                String filePath = intent.getStringExtra(FILE_KEY);
                onCreateDialog(filePath);
            }
        }
    };

    /**
     * 收到下载完成的广播，提示用户安装
     */
    private void onCreateDialog(final String filePath) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
                alertDialog.setMessage("新版本已下载，是否现在安装?")
                        .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                InstallUtil.INSTANCE.installApk(filePath, MainActivity.this);
                                dialog.dismiss();
                            }
                        })
                        .setCancelable(false)
                        .create().show();
            }
        });
    }
}
